package cae.logic.destination;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class CaeGroupManager {

	private static CaeGroupManager instance;
	private List<CaeGroup> groups;
	private static final String GROUPS_FILE = "groups.xml";
	private static XStream xstream = new XStream(new DomDriver()); 
	private static Logger logger = Logger.getLogger(CaeGroupManager.class);
	
	public static CaeGroupManager getInstance()
	{
		if(instance == null)
			instance = new CaeGroupManager();
		return instance;
	}
	
	private CaeGroupManager()
	{
		xstream.alias("group", CaeGroup.class);
		load();
	}

	@SuppressWarnings("unchecked")
	private void load()
	{
		try
		{
			InputStream file = new FileInputStream(GROUPS_FILE);
			groups = (List<CaeGroup>)xstream.fromXML(file);
			file.close();
		}
		catch(Exception e)
		{
			logger.fatal("Error en la carga del archivo de groups ", e);
			throw new RuntimeException("Error en la carga del archivo de groups ", e);
		}
	}
	
	private void save()
	{
		try
		{
			OutputStream file = new FileOutputStream(GROUPS_FILE);
			xstream.toXML(groups, file);
			file.close();
		}
		catch(Exception e)
		{
			logger.fatal("Error en la escritura del archivo de groups ", e);
			throw new RuntimeException("Error en la escritura del archivo de groups ", e);
		}
	}

	public List<CaeGroup> getGroups() {
		return groups;
	}
	
	public CaeGroup getDestination(String nick)
	{
		for(CaeGroup g : groups)
		{
			if(g.getNick().equalsIgnoreCase(nick))
			{
				return g;
			}
		}
		return null;
	}
	
	public void addGroup(CaeGroup group) throws CaeDestinationException
	{
		if( getGroup(group.getNick()) != null)
			throw new CaeDestinationException("El grupo ya existe");
		groups.add(group);
		save();
	}
	
	public CaeGroup getGroup(String nick) 
	{
		for(CaeGroup g : groups)
		{
			if(g.getNick().equalsIgnoreCase(nick))
			{
				return g;
			}
		}
		return null;
	}
	
	public void deleteGroup(CaeGroup group)
	{
		groups.remove(group);
		save();
	}
}
